const app = new Vue({
  el: '#app',
  data: {
    books: [
      {
        id: 1,
        name: '《算法导论》',
        date: '2006-9',
        price: 85.00,
        count: 1
      },
      {
        id: 2,
        name: '《UNIX编程艺术》',
        date: '2006-2',
        price: 59.00,
        count: 1
      },
      {
        id: 3,
        name: '《编程珠玑》',
        date: '2008-10',
        price: 39.00,
        count: 1
      },
      {
        id: 4,
        name: '《代码大全》',
        date: '2006-3',
        price: 128.00,
        count: 1
      }
    ]
  },
  computed: {
    totalPrice() {
      let totalPrice = 0;

      // 普通的for循环
      // for (let i = 0; i < this.books.length; i++) {
      //   totalPrice += this.books[i].price * this.books[i].count;
      // }

      // for(let i in this.books)
      // let totalPrice = 0
      // for (let i in this.books) {
      //   totalPrice += this.books[i].price * this.books[i].count;
      // }

      // for (let i of this.books)
      // for (let i of this.books) {
      //   totalPrice += i.price * i.count;
      // }
      // return totalPrice;

      return this.books.reduce(function (preValue, book) {
        return preValue + book.count * book.price
      }, 0)

    }
  },
  methods: {
    add(index) {
      this.books[index].count++;
    },
    sub(index) {
      this.books[index].count--;
    },
    remove(index) {
      this.books.splice(index, 1);
    },
    getFinalPrice(price) {
      return '￥' + price.toFixed(2)
    }
  },
  filters: {
    showPrice(price) {
      return '￥' + price.toFixed(2);
    }
  }
})

// const nums = [10, , 222, 333, 555, 444, 20, 30, 40]
// // filter中的回调函数必须返回一个布尔值boolean
// // true 函数内部自动讲这回调的n加入到新的数组中
// // false 函数内部会过滤这次的n
// let nums2 = nums.filter(function (n) {
//   return n < 100
// })
// console.log(nums2)

// // map
// let nums3 = nums2.map(function (n) {
//   return n * 2
// })
// console.log(nums3)

// // reduce 对数组中所有的内容进行汇总

// let nums4 = nums3.reduce(function (preValue, n) {
//   return preValue + n
// }, 0)

// console.log(nums4)
